// lib/pages/anion_page.dart
// ======================================================
// 负离子页面（自动关闭 + 工作时间 + 趋势图带网格 + 记录小图标）
// ======================================================

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controllers/device_manager_controller.dart';
import '../widgets/common_bottom_nav.dart';
import 'widgets/temp_chart.dart'; // 你已有的折线图

class AnionPage extends StatefulWidget {
  const AnionPage({Key? key}) : super(key: key);

  @override
  State<AnionPage> createState() => _AnionPageState();
}

class _AnionPageState extends State<AnionPage> {
  final dm = Get.find<DeviceManagerController>();   //

  // 最近 15 条记录
  final List<AnionPoint> history = [];

  // 用户设置的工作时间 (0~30)
  int workMinutes = 30;

  // 倒计时剩余秒
  int workRemaining = 0;

  Timer? _dataTimer;  // 每 2 秒加一次记录
  Timer? _workTimer;  // 倒计时

  @override
  void initState() {
    super.initState();
    _startTimers();
  }

  void _startTimers() {
    _stopTimers();

    // 数据刷新
    _dataTimer = Timer.periodic(const Duration(seconds: 2), (_) {
      if (!dm.anion.value) return;

      final value = _mockAnionValue();
      final now = DateTime.now();

      history.add(AnionPoint(now, value));
      if (history.length > 15) history.removeAt(0);

      setState(() {});
    });

    // 倒计时（每秒）
    _workTimer = Timer.periodic(const Duration(seconds: 1), (_) async {
      if (!dm.anion.value) return;

      if (workRemaining <= 0) {
        // 时间到了 → 自动关闭
        await dm.toggleAnion();
        setState(() {});
        return;
      }

      workRemaining--;
      setState(() {});
    });
  }

  void _stopTimers() {
    _dataTimer?.cancel();
    _workTimer?.cancel();
    _dataTimer = null;
    _workTimer = null;
  }

  @override
  void dispose() {
    _stopTimers();
    super.dispose();
  }

  // 模拟值
  int _mockAnionValue() {
    final sec = DateTime.now().second;
    return 300 + (sec * 70) % 2300;
  }

  // 空气等级
  AnionLevel _getLevel(int v) {
    if (v <= 300) return AnionLevel.normal;
    if (v <= 1000) return AnionLevel.good;
    return AnionLevel.excellent;
  }

  // 开启负离子（方案 B）
  Future<void> _turnOnAnion() async {
    await dm.setAnionWorkMinutes(workMinutes);
    workRemaining = workMinutes * 60;
    await dm.toggleAnion();
    setState(() {});
  }

  Future<void> _turnOffAnion() async {
    await dm.toggleAnion();
    setState(() {});
  }

  // ===========================
  // 设置工作时间
  // ===========================
  Future<void> _pickWorkMinutes() async {
    int temp = workMinutes;

    final result = await showModalBottomSheet<int>(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (ctx) {
        return StatefulBuilder(
          builder: (ctx, setStateSheet) {
            return Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Text("设置工作时间", style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold)),
                  const SizedBox(height: 12),
                  Text("$temp 分钟", style: const TextStyle(fontSize: 24)),
                  Slider(
                    min: 0,
                    max: 30,
                    divisions: 30,
                    value: temp.toDouble(),
                    label: "$temp 分钟",
                    onChanged: (v) => setStateSheet(() => temp = v.round()),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      TextButton(onPressed: () => Navigator.pop(ctx), child: const Text("取消")),
                      ElevatedButton(onPressed: () => Navigator.pop(ctx, temp), child: const Text("确定")),
                    ],
                  ),
                ],
              ),
            );
          },
        );
      },
    );

    if (result == null) return;

    setState(() {
      workMinutes = result;
    });

    if (dm.anion.value) {
      await dm.setAnionWorkMinutes(workMinutes);
      workRemaining = workMinutes * 60;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final isOn = dm.anion.value;

      return Scaffold(
        backgroundColor: const Color(0xFFF7F8FA),
        body: Column(
          children: [
            _buildHeader(isOn),
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(20),
                child: Column(
                  children: [
                    _buildValueCard(isOn),
                    const SizedBox(height: 15),
                    _buildLevelCard(isOn),
                    const SizedBox(height: 20),
                    _buildWorkTimeRow(),
                    const SizedBox(height: 20),
                    _buildTrendChart(),
                    const SizedBox(height: 25),
                    _buildHistoryList(),
                  ],
                ),
              ),
            )
          ],
        ),
        bottomNavigationBar: const CommonBottomNav(),
      );
    });
  }

  // -------------- UI ---------------

  Widget _buildHeader(bool isOn) {
    return Container(
      padding: EdgeInsets.only(
        top: MediaQuery.of(context).padding.top + 8,
        left: 16,
        right: 16,
        bottom: 12,
      ),
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
              onTap: () => Get.back(),
              child: const Icon(Icons.arrow_back, size: 24)),
          const Text("负离子", style: TextStyle(fontSize: 20,fontWeight: FontWeight.w600)),

          GestureDetector(
            onTap: () async {
              if (isOn) {
                await _turnOffAnion();
              } else {
                await _turnOnAnion();
              }
            },
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
              decoration: BoxDecoration(
                color: isOn ? Colors.blueAccent : Colors.grey.shade300,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Text(
                isOn ? "ON" : "OFF",
                style: TextStyle(
                    color: isOn ? Colors.white : Colors.black87,
                    fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildValueCard(bool isOn) {
    final v = isOn && history.isNotEmpty ? history.last.value : 0;

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 30),
      width: double.infinity,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(20),
        gradient: const LinearGradient(
            colors: [Color(0xFFEAF4FF), Color(0xFFDDEBFF)],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight),
      ),
      child: Column(
        children: [
          Text("$v", style: const TextStyle(fontSize: 46, fontWeight: FontWeight.bold, color: Colors.blueAccent)),
          const SizedBox(height: 4),
          Text(isOn ? "个/cm³" : "已关闭", style: const TextStyle(fontSize: 15,color: Colors.black54)),
        ],
      ),
    );
  }

  Widget _buildLevelCard(bool isOn) {
    if (!isOn || history.isEmpty) {
      return Container(
        width: double.infinity,  // 添加这一行
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
            color: Colors.grey.shade200,
            borderRadius: BorderRadius.circular(14)),
        child: const Text("负离子功能已关闭", style: TextStyle(color: Colors.black54)),
      );
    }

    final v = history.last.value;
    final level = _getLevel(v);

    return Container(
      width: double.infinity,  // 添加这一行
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: level.color.withOpacity(0.12),
        borderRadius: BorderRadius.circular(14),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(level.label,
              style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold,color: level.color)),
          const SizedBox(height: 6),
          Text(level.desc, style: TextStyle(fontSize: 14, color: level.color)),
        ],
      ),
    );
  }

  // 工作时间行
  Widget _buildWorkTimeRow() {
    final showRemain = dm.anion.value;

    return GestureDetector(
      onTap: _pickWorkMinutes,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(14),
            boxShadow: [
              BoxShadow(color: Colors.grey.shade200, blurRadius: 6)
            ]),
        child: Row(
          children: [
            const Icon(Icons.timer_outlined, color: Colors.blueAccent),
            const SizedBox(width: 8),
            const Text("工作时间", style: TextStyle(fontSize: 15)),

            const Spacer(),

            Text(
              showRemain
                  ? "剩余 ${(workRemaining / 60).ceil()} 分钟"
                  : "$workMinutes 分钟",
              style: const TextStyle(fontSize: 15,fontWeight: FontWeight.w500),
            ),
            const SizedBox(width: 4),
            const Icon(Icons.chevron_right, color: Colors.grey),
          ],
        ),
      ),
    );
  }

  // ===========================
  // 趋势图（带网格线）
  // ===========================
  Widget _buildTrendChart() {
    final points = history
        .map((p) => TempPoint(p.time, p.value.toDouble()))
        .toList();

    return Container(
      height: 220,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(14)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text("空气质量指数趋势",
              style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
          const SizedBox(height: 8),

          Expanded(
            child: points.isEmpty
                ? const Center(child: Text("暂无数据", style: TextStyle(color: Colors.black45)))
                : ChartWithGrid(
              child: TempChart(points: points),
            ),
          ),
        ],
      ),
    );
  }

  // ===========================
  // 历史记录
  // ===========================
  Widget _buildHistoryList() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(14)),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text("净化记录", style: TextStyle(fontSize: 15)),
              GestureDetector(
                onTap: () {
                  history.clear();
                  setState(() {});
                },
                child: Row(
                  children: const [
                    Icon(Icons.cleaning_services_outlined,
                        color: Colors.blue),
                    SizedBox(width: 4),
                    Text("清除全部",
                        style: TextStyle(color: Colors.blue,fontSize: 14)),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),

          if (history.isEmpty)
            const Align(
                alignment: Alignment.centerLeft,
                child: Text("暂无记录",
                    style: TextStyle(color: Colors.black45))),

          ...history.reversed.map((p) {
            final level = _getLevel(p.value);
            final t =
                "${p.time.hour.toString().padLeft(2, '0')}:${p.time.minute.toString().padLeft(2, '0')}";

            return Container(
              margin: const EdgeInsets.only(bottom: 10),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey.shade300),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(t),
                  Row(
                    children: [
                      const Icon(Icons.eco, color: Colors.green, size: 18),
                      const SizedBox(width: 4),
                      Text("${p.value}个/cm³"),
                    ],
                  ),
                  Row(
                    children: [
                      Text(level.label, style: TextStyle(color: level.color)),
                      const SizedBox(width: 4),
                      const Icon(Icons.chevron_right, color: Colors.grey),
                    ],
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }
}

// =======================================================
// 包装网格背景
// =======================================================
class ChartWithGrid extends StatelessWidget {
  final Widget child;
  const ChartWithGrid({required this.child});

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      foregroundPainter: _GridPainter(),
      child: child,
    );
  }
}

// 网格线 Painter
class _GridPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.grey.shade300
      ..strokeWidth = 0.6;

    const rows = 5;
    const cols = 5;

    final dx = size.width / cols;
    final dy = size.height / rows;

    // 横线
    for (int i = 1; i < rows; i++) {
      canvas.drawLine(Offset(0, dy * i), Offset(size.width, dy * i), paint);
    }

    // 竖线
    for (int i = 1; i < cols; i++) {
      canvas.drawLine(Offset(dx * i, 0), Offset(dx * i, size.height), paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

// 数据模型
class AnionPoint {
  final DateTime time;
  final int value;
  AnionPoint(this.time, this.value);
}

// 空气等级
enum AnionLevel { normal, good, excellent }

extension AnionLevelExt on AnionLevel {
  String get label => ["初始", "舒然", "优良"][index];

  String get desc => [
    "负离子浓度偏低，空气宁静微漾。",
    "负离子浓度逐渐升高，空气清新舒爽。",
    "负离子浓度适中，空气清新怡人。"
  ][index];

  Color get color => [Colors.redAccent, Colors.orangeAccent, Colors.green][index];
}
